import os
import signal

import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
from tornado.web import URLSpec, StaticFileHandler

from common.api.service_center import start_listen_service
from common.conf import PROJECT_NAME
from web_module.handler.log import init_async_task
from web_module.handler.main import MainHandler
from web_module.handler.security import SecurityHandler

define("port", type=int, default=8001, help="run on the given port")
urls = [
    URLSpec(r"/%s/web/static/(.*)" % PROJECT_NAME, StaticFileHandler, {"path": 'static'}),
    (r'/%s/web/security/request_pk' % PROJECT_NAME, SecurityHandler),

    # url: /PROJECT_NAME/module_name/file/function
    (r'/%s/(?P<module>\w+)/(?P<handler>\w+)/(?P<func>\w+)' % PROJECT_NAME, MainHandler),
]


# 定义服务器
def main():
    # 开启监听服务的变化
    start_listen_service()
    # 解析命令行参数
    tornado.options.parse_command_line()
    # 创建应用实例
    app = tornado.web.Application(handlers=urls)
    # 监听端口
    app.listen(options.port)
    # 创建IOLoop实例并启动
    tornado.ioloop.IOLoop.current().start()


# 应用运行入口，解析命令行参数
if __name__ == "__main__":
    init_async_task()
    # 启动服务器
    try:
        main()
    except BaseException as e:
        print(e)
        os.kill(os.getpid(), signal.SIGKILL)
